package com.moyoutian.line.queue;


/**
 * 数组实现队列
 */
public class ArrayQueue<D> implements Queue<D> {

    private final D[] array;

    private final int length;

    /**
     * 队列头元素下标
     */
    private int headerIndex = 0;

    /**
     * 队列尾元素下标
     */
    private int tailIndex = 0;


    /**
     * 队列尾元素下标
     */
    private int count = 0;

    /**
     * @param length 队列长度
     */
    public ArrayQueue(int length) {
        this.length = length;
        this.array = (D[]) new Object[length];
    }


    /**
     * 判断当前队列是否为空
     *
     * @return 判断当前队列是否为空
     */
    private boolean isEmpty() {
        return count == 0;
    }

    /**
     * 判断当前队列是否已满
     *
     * @return 判断当前队列是否已满
     */
    private boolean isFull() {
        return count == length;
    }

    @Override
    public int getSize() {
        return 0;
    }

    @Override
    public int getMaxSize() {
        return this.length;
    }

    @Override
    public void add(D d) {
        if (isFull()) {
            throw new RuntimeException("添加失败，队列已满！");
        }
        array[headerIndex] = d;
        if (headerIndex++ >= length - 1) {
            headerIndex = length - headerIndex;
        }
        count++;
    }

    @Override
    public D getAndRemove() {
        if (isEmpty()) {
            throw new RuntimeException("获取元素失败，队列已空！");
        }
        D val = array[tailIndex];
        if (tailIndex++ >= length - 1) {
            tailIndex = length - tailIndex;
        }
        count--;
        return val;
    }

    @Override
    public D getHeader() {
        return array[tailIndex];
    }
}
